import { Inject, Provide } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import * as ipdb from 'ipip-ipdb';
import * as _ from 'lodash';
import * as moment from 'moment';

/**
 * 帮助类
 */
@Provide()
export class Utils {
  @Inject()
  baseDir;

  /**
   * 获得请求IP
   */
  async getReqIP(ctx: Context) {
    const req = ctx.req;
    return (
      req.headers['x-forwarded-for'] ||
      req.socket.remoteAddress.replace('::ffff:', '')
    );
  }

  /**
   * 去除对象的空值属性
   * @param obj
   */
  async removeEmptyP(obj) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '' || obj[key] === 'undefined') {
        delete obj[key];
      }
    });
  }

  /**
   * 线程阻塞毫秒数
   * @param ms
   */
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**
   * 获得最近几天的日期集合
   * @param recently
   */
  getRecentlyDates(recently, format = 'YYYY-MM-DD') {
    moment.locale('zh-cn');
    const dates = [];
    for (let i = 0; i < recently; i++) {
      dates.push(moment().subtract(i, 'days').format(format));
    }
    return dates.reverse();
  }
  /**
   * 获得最近几个月的月数
   * @param recently
   */
  getRecentlyMonths(recently, format = 'YYYY-MM') {
    moment.locale('zh-cn');
    const dates = [];
    const date = moment(Date.now()).format('YYYY-MM');
    for (let i = 0; i < recently; i++) {
      dates.push(moment(date).subtract(i, 'months').format(format));
    }
    return dates.reverse();
  }

  /**
   * 根据开始和结束时间，获得时间段内的日期集合
   * @param start
   * @param end
   */
  getBetweenDays(start, end, format = 'YYYY-MM-DD') {
    moment.locale('zh-cn');
    const dates = [];
    const startTime = moment(start).format(format);
    const endTime = moment(end).format(format);
    const days = moment(endTime).diff(moment(startTime), 'days');
    for (let i = 0; i <= days; i++) {
      dates.push(moment(startTime).add(i, 'days').format(format));
    }
    return dates;
  }

  /**
   * 根据开始和结束时间，获得时间段内的月份集合
   * @param start
   * @param end
   */
  getBetweenMonths(start, end, format = 'YYYY-MM') {
    moment.locale('zh-cn');
    const dates = [];
    const startTime = moment(start).format(format);
    const endTime = moment(end).format(format);
    const months = moment(endTime).diff(moment(startTime), 'months');
    for (let i = 0; i <= months; i++) {
      dates.push(moment(startTime).add(i, 'months').format(format));
    }
    return dates;
  }

  /**
   * 根据开始和结束时间，获得时间段内的小时集合
   * @param start
   * @param end
   */
  getBetweenHours(start, end, format = 'YYYY-MM-DD HH') {
    moment.locale('zh-cn');
    const dates = [];
    const startTime = moment(start).format(format);
    const endTime = moment(end).format(format);
    const hours = moment(endTime).diff(moment(startTime), 'hours');
    for (let i = 0; i <= hours; i++) {
      dates.push(moment(startTime).add(i, 'hours').format(format));
    }
    return dates;
  }

  /**
   * 字段转驼峰法
   * @param obj
   * @returns
   */
  toCamelCase(obj) {
    let camelCaseObject = {};
    for (let i in obj) {
      let camelCase = i.replace(/([-_][a-z])/gi, $1 => {
        return $1.toUpperCase().replace('-', '').replace('_', '');
      });
      camelCaseObject[camelCase] = obj[i];
    }
    return camelCaseObject;
  }

}


function getWeekDates(direction) {
  let now: any = new Date();
  let dayOfWeek = now.getDay(); // 0 (Sunday) to 6 (Saturday)
  let dayOffset = dayOfWeek - 1; // 使星期一为一周的开始
  let startDate = new Date(now - dayOffset * 24 * 60 * 60 * 1000); // 本周开始日期
  let endDate = new Date(startDate.getTime() + 6 * 24 * 60 * 60 * 1000); // 本周结束日期

  if (direction === 'previous') {
    startDate.setDate(startDate.getDate() - 7); // 上一周开始日期
    endDate.setDate(endDate.getDate() - 7); // 上一周结束日期
  }

  if (direction === 'lastDay') {
    startDate.setDate(startDate.getDate() - 1); // 昨天
    endDate.setDate(endDate.getDate() - 1); // 上一周结束日期
  }

  return {
    start: startDate,
    end: endDate
  };
}

// 实时更新时间的函数
function updateTime(dateTime: any = new Date(), types) {
  function padZero(num) {
    return num < 10 ? '0' + num : num;
  }
  const now = dateTime;
  let year = now.getFullYear() + ''
  let _mount = now.getMonth() + 1
  let _day = now.getDate()
  let endTime = types == 1 ? ' 00:00:00' : ' 23:59:59'
  let hours = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();

  let formattedHours = padZero(hours);
  let formattedMinutes = padZero(minutes);
  let formattedSeconds = padZero(seconds);

  return year + '-' + padZero(_mount) + '-' + padZero(_day) + endTime
}

export {
  getWeekDates,
  updateTime
}